<template>
  <el-upload
      v-model:file-list="fileList"
      :before-upload="handleBeforeUpload" :http-request="uploadRequest" :limit="maxCount"
      :list-type="listType"
      :multiple="true"
      :on-exceed="handleExceed"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :show-file-list="showFileList"
      accept="imageTypes"
  >
    <el-button type="success">上传文件</el-button>
    <template #tip>
      <div class="el-upload__tip">
        只能上传xxx文件，且不超过10MB
      </div>
    </template>
  </el-upload>
  <el-image-viewer v-if="imagePreviewVisible"
                   :url-list="modelValue"
                   hide-on-click-modal @close="closePreview"
  />
</template>

<script setup>
import {ref, watch} from "vue";
import {useFormItem} from "element-plus";
import {getUploadPresigned, uploadByPresignedUrl} from "@/apis/file";

const props = defineProps({
  modelValue: {
    type: Array,
    default: []
  },
  maxCount: {
    type: Number,
    default: 30
  },
  listType: {
    type: String,
    default: "text"
  },
  showFileList: {
    type: Boolean,
    default: true
  }
})
const emits = defineEmits(["update:modelValue"])

const imageTypes = "png,jpg,jpeg";

const fileList = ref([])
//预览
const imagePreviewVisible = ref(false)


const handleExceed = () => {
  ElMessage.warning(`最多只能上传${props.maxCount}张图片`)
}
/**
 * 限制用户上传文件的格式和大小
 */
const handleBeforeUpload = rawFile => {
  const typeArr = imageTypes.split(",")
  let flag = false
  for (const type of typeArr) {
    if (rawFile.type.includes(type)) {
      flag = true
      break
    }
  }
  if (!flag) {
    ElMessage.error("很抱歉您上传的不是png,jpg,jpeg格式");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error("您上传的图片大小超过了10MB");
    return false;
  }
  //获取预签名URL
  getUploadPresigned(rawFile.name).then(({data}) => {
    //根据预签名URL上传文件
    uploadByPresignedUrl(data, rawFile).then(() => {
      emits("update:modelValue", [...props.modelValue, data.slice(0, data.indexOf("?"))])
      ElMessage.success("上传成功")
    })
  })
}

/**
 *  自定义上传函数替换掉原来的处理逻辑，防止根据action上传报错而无法回显fileList
 */
const uploadRequest = () => {
}

/**
 * 点击图片列表时
 */
const handlePreview = () => {
  imagePreviewVisible.value = true
}
const closePreview = () => {
  imagePreviewVisible.value = false
}
/**
 *  删除图片时
 */
const handleRemove = () => {
  emits("update:modelValue", fileList.value.map(value => value.url))
}

//自定义组件触发校验
const {formItem} = useFormItem()
watch(() => props.modelValue, () => {
  fileList.value = props.modelValue.map(value => {
    return {
      url: value,
      name: value.slice(value.lastIndexOf("/") + 1)
    }
  })
  formItem?.validate('change')
})
</script>

<style lang="scss" scoped>
.upload-preview {
  padding: 0 5em 0 5em;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
}
</style>
